java上传文件到ftp服务器

2024-09-28 15:25:39 38 Admin
建网站服务

 

在Java中,可以使用Apache Commons Net库来实现将文件上传到FTP服务器。下面是一个简单的示例代码:

 

```java

import org.apache.commons.net.ftp.FTP;

import org.apache.commons.net.ftp.FTPClient;

 

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

 

public class FTPUploader {

private static final int BUFFER_SIZE = 4096;

 

public static void main(String[] args) {

String server = "ftp.example.com";

int port = 21;

String username = "your_username";

String password = "your_password";

String localFilePath = "path_to_local_file";

String remoteFilePath = "path_to_remote_file";

 

FTPClient ftpClient = new FTPClient();

try {

ftpClient.connect(server

port);

ftpClient.login(username

password);

ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

 

File localFile = new File(localFilePath);

FileInputStream inputStream = new FileInputStream(localFile);

 

ftpClient.storeFile(remoteFilePath

inputStream);

inputStream.close();

 

System.out.println("File uploaded successfully.");

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (ftpClient.isConnected()) {

ftpClient.logout();

ftpClient.disconnect();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

```

 

在上面的示例代码中,需要替换以下参数:

 

- `server`:FTP服务器的主机名或IP地址。

- `port`:FTP服务器的端口号,默认是21。

- `username`:登录FTP服务器的用户名。

- `password`:登录FTP服务器的密码。

- `localFilePath`:本地文件的路径。

- `remoteFilePath`:远程文件的路径。

 

请注意,上述代码仅仅上传了一个文件,如果需要上传多个文件,可在 `main` 方法中使用循环来实现。

 

希望这能帮助到你,如果还有其他问题,请随时提问。

Copyright © 悉地网 2018-2024.All right reserved.Powered by XIDICMS 备案号:苏ICP备18070416号-1